package me.seu.demo.controller;

import me.seu.demo.dto.DataGrid;
import me.seu.demo.model.Picture;
import me.seu.demo.service.PictureService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * MongoDB 增删改查 API
 *
 * @author liangfeihu
 * @since 2020/4/28 10:59
 */
@RestController
@RequestMapping(value = "/mongodb")
public class MongoCrudController {

    @Resource(name = "pictureService")
    private PictureService pictureService;

    @RequestMapping(value = "/pictures", method = RequestMethod.GET)
    public DataGrid<Picture> getPicList(@RequestParam("current") int current, @RequestParam("rowCount") int rowCount,
                                        @RequestParam(required = false, value = "sort[id]") String sortId,
                                        @RequestParam(required = false, value = "searchPhrase") String searchPhrase) {
        if (StringUtils.isBlank(searchPhrase)) {
            List<Picture> list = pictureService.getPicList(current, rowCount, sortId);
            int total = pictureService.getPictureNum();
            DataGrid<Picture> grid = new DataGrid<Picture>();
            grid.setCurrent(current);
            grid.setRowCount(rowCount);
            grid.setRows(list);
            grid.setTotal(total);
            return grid;
        } else {
            List<Picture> list = pictureService.getSearchResult(current, rowCount, sortId, searchPhrase);
            int total = pictureService.getSearchResultTotal(searchPhrase);
            DataGrid<Picture> grid = new DataGrid<Picture>();
            grid.setCurrent(current);
            grid.setRowCount(rowCount);
            grid.setRows(list);
            grid.setTotal(total);
            return grid;
        }
    }

    @RequestMapping(value = "/picture/delete/{id}", method = RequestMethod.GET)
    public String deletePicture(@PathVariable("id") String id) {
        pictureService.deletePicture(id);
        return "success";
    }


    @RequestMapping(value = "/picture/{id}", method = RequestMethod.GET)
    public Picture getPicture(@PathVariable("id") String id) {
        Picture p = pictureService.getPictureById(id);
        return p;
    }

    /**
     * 创造的测试数据
     */
    @RequestMapping(value = "add", method = RequestMethod.GET)
    public String ddd() {
        for (int i = 0; i < 1000; i++) {
            Picture p = new Picture("w" + i, "java" + i, (long) i);
            pictureService.saveOrUpdatePicture(p);
        }
        return "success";
    }
}
